package edu.maine.usm.client;

import java.util.ArrayList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;

import edu.maine.usm.dto.PatientDTO;
import edu.maine.usm.rpc.EnrollmentServiceAsync;
import edu.maine.usm.rpc.OpenMRSClientServiceAsync;
import com.google.gwt.user.cellview.client.SimplePager;

public class AlertEventView extends Composite {

	private static AlertEventViewUiBinder uiBinder = GWT
			.create(AlertEventViewUiBinder.class);
	
	@UiField Button searchBtn;
	@UiField InputElement openmrsPatientName;
	@UiField DivElement statusMsg;
	@UiField(provided=true) CellTable<PatientDTO> cellTable = new CellTable<PatientDTO>();
	@UiField SimplePager pager;

	private EnrollmentServiceAsync service;
	private OpenMRSClientServiceAsync openmrsService;
	private ListDataProvider<PatientDTO> provider = new ListDataProvider<PatientDTO>();
	
	interface AlertEventViewUiBinder extends UiBinder<Widget, AlertEventView> {
	}

	public AlertEventView(EnrollmentServiceAsync service, OpenMRSClientServiceAsync openmrsService) {
		this.service = service;
		this.openmrsService = openmrsService;
		initWidget(uiBinder.createAndBindUi(this));
		cellTable.addColumn(new TextColumn<PatientDTO>(){
			@Override
			public String getValue(PatientDTO object) {
				return object.getMotechIdentifier();
			}
		}, "MoTeCH Id");
		cellTable.addColumn(new TextColumn<PatientDTO>() {
			@Override
			public String getValue(PatientDTO object) {
				return object.getFirstName();
			}
		}, "First Name");
		cellTable.addColumn(new TextColumn<PatientDTO>() {
			@Override
			public String getValue(PatientDTO object) {
				return object.getLastName();
			}
		}, "Last Name");
		
		provider.addDataDisplay(cellTable);
		pager.setDisplay(cellTable);
	}
	
	@UiHandler("searchBtn")
	public void handleFireEvent(ClickEvent event) {
		openmrsService.searchPatient(openmrsPatientName.getValue(), new AsyncCallback<ArrayList<PatientDTO>>() {
			public void onFailure(Throwable caught) {
				statusMsg.setInnerHTML("Failed to search for patient");
			}

			public void onSuccess(ArrayList<PatientDTO> result) {
				setProviderData(result);
			}
		});
	}
	
	private void setProviderData(ArrayList<PatientDTO> data) {
		provider.setList(data);
	}

}
